package com.study.cloud.gateway.core.netty;

import com.study.cloud.gateway.core.config.Config;
import com.study.cloud.gateway.core.cycle.LifeCycle;
import com.study.cloud.gateway.core.helper.AsyncHttpHelper;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.EventLoopGroup;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;

import java.io.IOException;

/**
 * 对下游的请求转发
 * @author wangwancheng
 * @create 2025/7/19 10:19
 */
public class NettyHttpClient implements LifeCycle {

    private final Config config;

    private final EventLoopGroup workGroup;

    private AsyncHttpClient asyncHttpClient;

    public NettyHttpClient(Config config, EventLoopGroup workGroup) {
        this.config = config;
        this.workGroup = workGroup;
        init();
    }


    @Override
    public void init() {
        DefaultAsyncHttpClientConfig.Builder builder = new DefaultAsyncHttpClientConfig.Builder();
        // 设置线程数
        builder.setEventLoopGroup(workGroup)
                //设置链接超时
                .setConnectTimeout(config.getHttpConnectTimeout())
                //设置请求超时
                .setRequestTimeout(config.getHttpRequestTimeout())
                //转发重试次数
                .setMaxRedirects(config.getHttpRetryTimes())
                //缓冲区分配器 池化分配器
                .setAllocator(PooledByteBufAllocator.DEFAULT)
                //压缩
                .setCompressionEnforced(true)
                //最大链接书
                .setMaxConnections(config.getHttpMaxConnections())
                //每个客户端支持的最大链接数
                .setMaxConnectionsPerHost(config.getHttpMaxConnectionsPerHost())
                //客户端空闲链接超时时间
                .setPooledConnectionIdleTimeout(config.getHttpPoolConnectionIdleTimeout());
        this.asyncHttpClient = new DefaultAsyncHttpClient(builder.build());


    }

    @Override
    public void start() {
        AsyncHttpHelper.getInstance().initialized(asyncHttpClient);
    }

    @Override
    public void shutdown() {
        if (asyncHttpClient != null){
            try {
                asyncHttpClient.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
